using MediatR;
using Microsoft.AspNetCore.Mvc;
using SupplierCustomerManagement.Read.API.Applications.Commands.suppliers;

using B.S.RbacData.ErrorCode;

namespace SupplierCustomerManagement.Read.API.Controllers
{
    /// <summary>
    /// 供应商查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class SuppliersController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<SuppliersController> _logger;

        public SuppliersController(IMediator mediator, ILogger<SuppliersController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取供应商列表
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>供应商列表</returns>
        [HttpGet]
        public async Task<ActionResult<ApiPaging<SupplierListDto>>> GetSuppliers([FromQuery] GetSuppliersQuery query)
        {
            try
            {

                var result = await _mediator.Send(query);

                _logger.LogInformation("成功处理获取供应商列表请求，返回 {Count} 条记录", 
                    result.PageData?.Count ?? 0);

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取供应商列表请求时发生异常");
                
                var errorResult = new ApiPaging<SupplierListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取供应商列表失败: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<SupplierListDto>()
                };

                return StatusCode(500, errorResult);
            }
        }

        /// <summary>
        /// 根据ID获取供应商详细信息
        /// </summary>
        /// <param name="id">供应商ID</param>
        /// <returns>供应商详细信息</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<ApiResult<SupplierDetailDto>>> GetSupplierById(int id)
        {
            try
            {
                var query = new GetSupplierByIdQuery(id);
                var result = await _mediator.Send(query);

                _logger.LogInformation("成功处理获取供应商详细信息请求，供应商ID: {SupplierId}", id);

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取供应商详细信息请求时发生异常，供应商ID: {SupplierId}", id);
                
                var errorResult = new ApiResult<SupplierDetailDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取供应商详细信息失败: {ex.Message}",
                    data = default
                };

                return StatusCode(500, errorResult);
            }
        }

    }
}